import cv2
import numpy as np
import matplotlib.pyplot as plt

# 读取图像并转换为灰度图像
image_path = '4.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Error: Unable to load image.")
    exit()

# 设置固定阈值
threshold_value = 128

# 1. 二进制阈值化
_, binary_threshold = cv2.threshold(image, threshold_value, 255, cv2.THRESH_BINARY)

# 2. 反二进制阈值化
_, inverse_binary_threshold = cv2.threshold(image, threshold_value, 255, cv2.THRESH_BINARY_INV)

# 3. 截断阈值化
_, truncated_threshold = cv2.threshold(image, threshold_value, 255, cv2.THRESH_TRUNC)

# 4. 反阈值化为0
_, inverse_threshold_to_zero = cv2.threshold(image, threshold_value, 255, cv2.THRESH_TOZERO_INV)

# 5. 阈值化为0
_, threshold_to_zero = cv2.threshold(image, threshold_value, 255, cv2.THRESH_TOZERO)

# 显示原始图像和各种阈值化后的图像
plt.figure(figsize=(12, 8))
plt.subplot(2, 3, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.axis('off')

plt.subplot(2, 3, 2)
plt.title('Binary Thresholding')
plt.imshow(binary_threshold, cmap='gray')
plt.axis('off')

plt.subplot(2, 3, 3)
plt.title('Inverse Binary Thresholding')
plt.imshow(inverse_binary_threshold, cmap='gray')
plt.axis('off')

plt.subplot(2, 3, 4)
plt.title('Truncated Thresholding')
plt.imshow(truncated_threshold, cmap='gray')
plt.axis('off')

plt.subplot(2, 3, 5)
plt.title('Inverse Thresholding to Zero')
plt.imshow(inverse_threshold_to_zero, cmap='gray')
plt.axis('off')

plt.subplot(2, 3, 6)
plt.title('Thresholding to Zero')
plt.imshow(threshold_to_zero, cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()